﻿using log4net;
using Rainbow.core;
using Rainbow.utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rainbow.model
{
    public class ConnectInfoCollection : SHCollection<ConnectInfo>
    {
        private static ILog logger = LogManager.GetLogger(typeof(ConnectInfoCollection));

        public ConnectInfoCollection() { }

        public ConnectInfoCollection(ConnectInfoCollection collection)
        {
            collection.ForEach(x =>
            {
                ConnectInfo info = new ConnectInfo(x);
                dataList.Add(info);
                return false;
            });
        }

        public override bool Equals(ConnectInfo obj, object key)
        {
            return (string)key == obj.name;
        }

        public override void CopyTo(ConnectInfo src, ConnectInfo dst)
        {
            dst.Copy(src);
        }

        public ConnectInfoCollection Clone()
        {
            return new ConnectInfoCollection(this);
        }

        public bool Save()
        {
            bool rn = true;

            rwLock.EnterReadLock();
            try
            {
                string dataFile = TW_App.fileManager.connectInfoFile;
                rn = XmlUtil.Save<ConnectInfoCollection>(dataFile, this);
            }
            finally
            {
                rwLock.ExitReadLock();
            }
            return rn;
        }

        public int Load()
        {
            int rn = -1;

            rwLock.EnterWriteLock();
            try
            {
                string dataFile = TW_App.fileManager.connectInfoFile;
                bool existsFlag = File.Exists(dataFile);
                if(!existsFlag)
                {
                    logger.WarnFormat("连接列表文件[{0}]不存在", dataFile);
                    return -2;
                }

                ConnectInfoCollection collection = XmlUtil.Load<ConnectInfoCollection>(dataFile);
                if(collection != null)
                {
                    dataList.Clear();
                    collection.ForEach(x =>
                    {
                        ConnectInfo data = x.Clone();
                        dataList.Add(data);
                        return false;
                    });

                    rn = 0;
                }
                else
                {
                    logger.ErrorFormat("加载连接文件[{0}]失败", dataFile);
                    rn = -1;
                }
            }
            finally
            {
                rwLock.ExitWriteLock();
            }
            return rn;
        }
    }
}
